package com.buka.recipe.food.service.impl;

import com.buka.recipe.food.entity.Food;
import com.buka.recipe.food.repository.FoodRepository;
import com.buka.recipe.food.service.FoodService;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {

    private final FoodRepository foodRepository;

    @Autowired
    public FoodServiceImpl(FoodRepository foodRepository) {
        this.foodRepository = foodRepository;
    }

    @Override
    public void save(Food food) {
        foodRepository.save(food);
    }

    @Override
    public void delete(Food food) {
        foodRepository.delete(food);
    }

    @Override
    public Food getFoodById(Integer id) {
        return foodRepository.findById(id).orElse(null);
    }

    @Override
    public Page<Food> getAll(String title, Integer current, Integer pageSize) {
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        Pageable pageable = PageRequest.of(current, pageSize, sort);
        Specification<Food> specification = (root, query, builder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasLength(title)) {
                list.add(builder.like(root.get("title"), "%" + title + "%"));
            }
            Predicate[] predicates = new Predicate[list.size()];
            return builder.and(list.toArray(predicates));
        };
        return foodRepository.findAll(specification, pageable);
    }

}
